package com.medicine.hbp.ui;

import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.kymjs.kjframe.http.HttpParams;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.medicine.hbp.R;
import com.medicine.hbp.download.NotificationUpdateActivity;
import com.medicine.hbp.http.AppHttpCallBack;
import com.medicine.hbp.http.AppHttps;
import com.medicine.hbp.http.HttpInterface;
import com.medicine.hbp.mob.DownloadVo;
import com.medicine.hbp.sp.LoginSp;
import com.medicine.hbp.sp.UtilsSp;
import com.medicine.hbp.uitl.BaiduApi;
import com.medicine.hbp.uitl.BaiduApi.OnBDLocationListener;
import com.medicine.hbp.uitl.CommUtil;
import com.medicine.hbp.uitl.MyApplication;
import com.medicine.hbp.uitl.ToastUtil;

/**
 * 首页
 *
 * @author Administrator
 *
 */

@SuppressWarnings("deprecation")
public class MainActivity extends TabActivity implements OnCheckedChangeListener {
	private static TabHost tabhost;
	private RadioGroup radioGroup;
	private RadioButton radio_button1, radio_button2;
	private static RadioButton radio_button3;
	private RadioButton radio_button4;
	private int tab = 0, tab2 = 0;;
	private MyApplication app;
	private String mykey = "AdviceSwift"; // key   1-打开    0-关闭
	private String defaultValue = "-1";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		CommUtil.destroySplashActivity();
		initTab();
	}

	private void initTab() {
		radio_button1 = (RadioButton) this.findViewById(R.id.radio_button1);
		radio_button2 = (RadioButton) this.findViewById(R.id.radio_button2);
		radio_button3 = (RadioButton) this.findViewById(R.id.radio_button3);
		radio_button4 = (RadioButton) this.findViewById(R.id.radio_button4);
		radioGroup = (RadioGroup) findViewById(R.id.main_radio);
		radioGroup.setOnCheckedChangeListener(this);

		// 实例化TabHost
		tabhost = this.getTabHost();
		// 1.首页
		Intent oneIntent = new Intent(this, HomeActivity.class);
		tabhost.addTab(tabhost.newTabSpec("ONE").setIndicator("ONE").setContent(oneIntent));
		Intent twoIntent = new Intent(this, MenuActivity.class);
		twoIntent.putExtra("type", true);
		tabhost.addTab(tabhost.newTabSpec("TWO").setIndicator("TWO").setContent(twoIntent));
		// 3.消息
		Intent threeIntent = new Intent(this, CardViewActivity.class);
		tabhost.addTab(tabhost.newTabSpec("THREE").setIndicator("THREE").setContent(threeIntent));
		Intent fourIntent = new Intent(this, SetActivity.class);
		tabhost.addTab(tabhost.newTabSpec("FOUR").setIndicator("FOUR").setContent(fourIntent));
		radio_button1.setChecked(true);
		tab = 1;
		app = (MyApplication) getApplication();
		JPushInterface.setAliasAndTags(this, "com.medicine.hbp"+LoginSp.getUserId(MainActivity.this), null, new TagAliasCallback() {
			@Override
			public void gotResult(int arg0, String arg1, Set<String> arg2) {
				if(arg0==0){
				}
			}
		});
		http();
//		httpYm();
		BaiduApi api=new BaiduApi(MainActivity.this,new OnBDLocationListener() {

			@Override
			public void onYes(String  pro, String city) {
				// TODO Auto-generated method stub
				httpUpdateCity(pro,city);
			}

			@Override
			public void onNo() {
				// TODO Auto-generated method stub

			}
		});
		api.StartBaidu();
	}

	@Override
	public void onCheckedChanged(RadioGroup arg0, int checkedId) {
		switch (checkedId) {
			case R.id.radio_button1:
				tab = 1;
				tabhost.setCurrentTabByTag("ONE");// 1.首页
				break;
			case R.id.radio_button2:
//			if (LoginSp.getUserId(this) != 0) {
//				tab = 2;
				tabhost.setCurrentTabByTag("TWO");// 2.投票
//			} else {
//				tab2 = 2;
//				StartIntent.MainStartLogin(this, tab);
//			}
				break;
			case R.id.radio_button3:
				tab = 3;
				tabhost.setCurrentTabByTag("THREE");// 3.消息
				break;
			case R.id.radio_button4:
//			if (LoginSp.getUserId(this) != 0) {
//				tab = 4;
				tabhost.setCurrentTabByTag("FOUR");// 4.我的
//			} else {
//				tab2 = 4;
//				StartIntent.MainStartLogin(this, tab);
//			}
				break;
		}

	}

//	private void httpYm() {
//		// 方法二： 异步调用（可在任意线程中调用）
//		AdManager.getInstance(MainActivity.this).asyncGetOnlineConfig(mykey,
//				new OnlineConfigCallBack() {
//					@Override
//					public void onGetOnlineConfigSuccessful(String key,String value) {
//						if(null!=value){
//							if(value.equals("1")){
//								UtilsSp.setIsYm(true, MainActivity.this);
//							}else{
//								UtilsSp.setIsYm(false, MainActivity.this);
//							}
//						}
////						Log.e("httpYm",value);
//						// 获取在线参数成功
//					}
//
//					@Override
//					public void onGetOnlineConfigFailed(String key) {
//						// TODO Auto-generated method stub
//						// 获取在线参数失败，可能原因有：键值未设置或为空、网络异常、服务器异常
//					}
//				});
//
//	}

	private void httpUpdateCity(String pro,String city) {
		HttpParams params = new HttpParams();
		params.put("userToken", CommUtil.getIMEI(MainActivity.this));
		params.put("pro", pro);
		params.put("city", city);
		AppHttps.HttpPost(this, HttpInterface.UPDATE_CITY, params,
				new AppHttpCallBack<Object>(Object.class,MainActivity.this) {
					@Override
					public void onSuccess(Object result) {
					}
					@Override
					public void onFailures(int errorCode, String errorMsg) {
						ToastUtil.showShort(MainActivity.this, errorMsg);
					}
				});
	}
	private void http() {
		HttpParams params = new HttpParams();
		AppHttps.HttpPost(this, HttpInterface.FILE_VERSION, params,
				new AppHttpCallBack<DownloadVo>(DownloadVo.class,
						MainActivity.this) {
					@Override
					public void onSuccess(DownloadVo result) {
						try {
							if (CommUtil.getVersionCode(MainActivity.this) < result.info.fileVersion) {
								if (CommUtil.getVersionCode(MainActivity.this) < result.info.fileMinVersion) {
									fileVersion(result.info.fileUrl,
											result.info.fileNote);
								} else {
									fileVersion(result.info.fileUrl,
											result.info.fileNote);
								}

							}
						} catch (Exception e) {

						}

					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
						ToastUtil.showShort(MainActivity.this, errorMsg);
					}
				});
	}

	private void fileVersion(final String url, String content) {
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setTitle("更新");
		builder.setMessage(content);
		builder.setNegativeButton("确定", new AlertDialog.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				app.setDownload(true);
				app.setApkUrl(url);
				Intent it = new Intent(MainActivity.this,
						NotificationUpdateActivity.class);
				startActivity(it);

			}
		});
		builder.setNeutralButton("继续使用", null);
		builder.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (tab2) {
				case 2:
					radio_button2.setChecked(true);
					tabhost.setCurrentTabByTag("TWO");// 1.发稿
					break;
				case 4:
					radio_button3.setChecked(true);
					tabhost.setCurrentTabByTag("FOUR");// 3.我的
					break;
			}
		} else {
			switch (tab) {
				case 1:
					radio_button1.setChecked(true);
					tabhost.setCurrentTabByTag("ONE");// 1.首页
					break;
				case 3:
					radio_button3.setChecked(true);
					tabhost.setCurrentTabByTag("THREE");// 3.消息
					break;
			}
		}

	}
	public static void setTab(int type){
		radio_button3.setChecked(true);
		tabhost.setCurrentTabByTag("THREE");
		CardViewActivity.setTab(type);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitBy2Click();
			return false;
		}
		return super.onKeyDown(keyCode, event);

	}

	private Boolean isExit = false;

	/**
	 * 双击返回退出
	 *
	 */
	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
		} else {
			isExit = false;
			finish();
		}
	}
}
